#include "../import/head.h"
#include "protocol_ssl.h"
#include "../data_struct/head.h"
#include "../global/head.h"
#include "../macro/head.h"
#include "../msg/head.h"

namespace xos_sgsj
{

    protocol_ssl::protocol_ssl()
    {
    }

    protocol_ssl::~protocol_ssl()
    {
    }

	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//

	int protocol_ssl::dis_compose( session * pSession, xos::i_buf * pBuf )
	{
		int ret = 0;

		xos_encrypt::i_encrypt * pEncrypt = pSession->m_pEncrypt;
		char dec_pwd[100] = { 0 };
		char pwd[100] = { 0 };
		int dec_len = 0;
		int len = 0;

		if( 0 == ret )
		{
			ret = g_pSysData->m_os.m_pSerial->un_pack_mem( pBuf, pwd, sizeof( pwd ), &len, 0 );
		}

		if( 0 == ret )
		{
			ret = pEncrypt->rsa_private_decrypt( pwd, len, dec_pwd, &dec_len );
		}

		if( 0 == ret )
		{
			ret = pEncrypt->set_aes_key( dec_pwd, 16 );
		}

		{
			data * p = g_pSysData->m_pPool->m_data_pool.GetItem();
			p->init();
			p->m_nMsg = MSG_SSL;
			p->m_bSuccess = ( 0 == ret );
			p->m_pSession = pSession;
			g_pSysData->notify( p );
			p = 0;
		}

		return ret;
	}

	int protocol_ssl::compose( tcp * pTcp )
	{
		int ret = 0;

		session * pSession = pTcp->m_pSession;
		xos_encrypt::i_encrypt * pEncrypt = pSession->m_pEncrypt;
		xos::i_buf * pBuf = 0;
		xos::i_msg * pMsg = 0;

		if( 0 == ret )
		{
			ret = g_pSysData->m_os.m_pXos->create( xos::i_xos::XOS_OBJ_BUF, (void **)&pBuf );
		}

		if( 0 == ret )
		{
			ret = g_pSysData->m_os.m_pSerial->pack_int8( pBuf, PROTOCOL_SSL );
		}

		if( 0 == ret )
		{
			ret = pEncrypt->generate_rsa_keys();
		}

		if( 0 == ret )
		{
			char key[100] = { 0 };
			int len = 0;
			pEncrypt->get_rsa_keys( key, &len, 0, 0 );
			ret = g_pSysData->m_os.m_pSerial->pack_mem( pBuf, key, len );
		}

		if( 0 == ret )
		{
			ret = g_pSysData->m_os.m_pXos->create( xos::i_xos::XOS_OBJ_MSG, (void **)&pMsg );
		}

		if( 0 == ret )
		{
			pMsg->set_int( 0, xos_package::MSG_COMPOSE_PACKAGE );
			pMsg->set_bool( 1, true );
			pMsg->set_bool( 2, false );
			pMsg->set_buf( 0, pBuf );
			pMsg->set_void( 0, pSession );
			pMsg->set_void( 1, pEncrypt );
			pSession->add_ref( 1 );
			g_pSysData->m_os.m_pPackage->request( pMsg );
			pBuf = 0;
			pMsg = 0;
		}

		if( pBuf )
		{
			pBuf->release();
			pBuf = 0;
		}

		if( pMsg )
		{
			pMsg->release();
			pMsg = 0;
		}

		return ret;
	}

} // xos_sgsj
